import jwt from 'jsonwebtoken'
import { query } from '../utils/db'
import type { OkPacket, RowDataPacket } from 'mysql2'
import { ResponseCode, sendSuccessResponse, sendErrorResponse } from '~/server/utils/response'

// 从环境变量获取密钥
const JWT_SECRET = process.env.JWT_SECRET || 'your-strong-secret-key-here'
const ACCESS_TOKEN_EXPIRES_IN = '1h'
const REFRESH_TOKEN_EXPIRES_IN = '7d'

// 存储 Refresh Token
async function storeRefreshToken(userId: number, token: string): Promise<void> {
  try {
    const decoded = jwt.decode(token) as {
      exp?: number,
      userId?: number,
      user_id?: string
    } | null

    if (!decoded || !decoded.userId || !decoded.user_id) {
      throw new Error('无效的令牌格式')
    }

    let expiresAt: Date
    if (decoded.exp) {
      expiresAt = new Date(decoded.exp * 1000)
    } else {
      expiresAt = new Date()
      expiresAt.setDate(expiresAt.getDate() + 7)
    }

    const sql = `
      INSERT INTO refresh_tokens (
        user_table_id, 
        user_id, 
        token, 
        expires_at
      ) VALUES (?, ?, ?, ?)
      ON DUPLICATE KEY UPDATE
        token = VALUES(token),
        expires_at = VALUES(expires_at),
        revoked = 0
    `

    const params = [
      decoded.userId,
      decoded.user_id,
      token,
      expiresAt
    ]

    const { results } = await query<OkPacket>(sql, params)
    const result = results[0]

    if (result.affectedRows === 0) {
      throw new Error('未能存储刷新令牌')
    }

  } catch (error) {
    console.error('存储刷新令牌失败:', error)
    throw new Error('无法存储刷新令牌')
  }
}

export default defineEventHandler(async (event) => {
  const body = await readBody(event)
  const { username, password } = body

  // 参数验证
  if (!username || !password) {
    return sendErrorResponse(event, ResponseCode.BAD_REQUEST, '需要用户名和密码')
  }

  // 查询用户
  const sql = `
    SELECT 
      u.id, u.user_id, u.username, u.password, u.disable, 
      r.role_id, r.role 
    FROM user u 
    LEFT JOIN role r ON u.role_id = r.role_id 
    WHERE u.username = ? 
    LIMIT 1
  `

  const { results } = await query<RowDataPacket[]>(sql, [username])
  const user = results[0]

  if (!user || user.password !== password) {
    return sendErrorResponse(event, ResponseCode.UNAUTHORIZED, '用户名或密码错误')
  }

  if (user.disable) {
    return sendErrorResponse(event, ResponseCode.FORBIDDEN, '账号已禁用')
  }

  // 生成两种 Token
  const accessToken = jwt.sign(
    {
      userId: user.id,
      user_id: user.user_id,
      role: user.role
    },
    JWT_SECRET,
    { expiresIn: ACCESS_TOKEN_EXPIRES_IN }
  )

  const refreshToken = jwt.sign(
    {
      userId: user.id,
      user_id: user.user_id
    },
    JWT_SECRET + '_REFRESH',
    { expiresIn: REFRESH_TOKEN_EXPIRES_IN }
  )

  // 存储 Refresh Token
  try {
    await storeRefreshToken(user.id, refreshToken)
  } catch (error) {
    console.error('存储刷新令牌失败:', error)
    return sendErrorResponse(
      event,
      ResponseCode.UNAUTHORIZED,
      '无法完成登录'
    )
  }

  return sendSuccessResponse(event, {
    accessToken,
    refreshToken,
    user: {
      id: user.id,
      user_id: user.user_id,
      username: user.username,
      role: user.role
    }
  }, '登录成功')
})